import {
    BrowserRouter as Router,
    Switch,
    Route,
    Link,
    useRouteMatch,
    useParams
} from "react-router-dom";

export default function CustomLink() {
    return (
        <Router>
            <div>
                <OldSchoolMenuLink activeOnlyWhenExact={true}
                to="/" label="Home"/>
                 <OldSchoolMenuLink
                to="/about" label="About"/>
                 <OldSchoolMenuLink
                to="/topic" label="Topic"/>
            </div>
            <Switch>
                <Route exact path="/">
                    <Home />
                </Route>
                <Route path="/about">
                    <About />
                </Route>
                <Route path="/topic">
                    <Topics />
                </Route>
            </Switch>
        </Router>
    )
}

function OldSchoolMenuLink({ label, to, activeOnlyWhenExact }) {
    //同一时刻只有一个match，match 的属性有：path、url、params、isExact
    let match = useRouteMatch({
        path: to,
        exact: activeOnlyWhenExact
    });
    console.log("match:");
    console.log(match);
    return (
        <div className={match?"active":""}>
            {match && ">"}
            <Link to={to}>{label}</Link>
        </div>
    );
}

function Home() {
    return (
        <div>
            <h2>Home</h2>
        </div>
    );
}

function About() {
    return (
        <div>
            <h2>About</h2>
        </div>
    );
}

//嵌套路由
function Topics(){
    let {url, path} = useRouteMatch();
    console.log("useRouteMatch:");
    console.log(useRouteMatch());
    console.log("Topics params:");
    console.log(useParams());
    return (
        <div>
            <h2>Topics</h2>
            <div>
                <ul>
                    <li>
                        <Link to={`${path}/rendering`}>rendering</Link>
                    </li>
                    <li>
                        <Link to={`${path}/components`}>components</Link>
                    </li>
                    <li>
                        <Link to={`${path}/props-v-state`}>props-v-state</Link>
                    </li>
                </ul>
                <Switch>
                    <Route exact path="/">
                        <div>please select a topic</div>
                    </Route>
                    <Route path={`${path}/:topicid`}>
                        <Topic/>
                    </Route>
                </Switch>
            </div>
        </div>
    );
}

function Topic(){
    //获取
    let {topicid} = useParams();
    console.log("useParams:");
    console.log(useParams());
    console.log("useRouteMatch:");
    console.log(useRouteMatch());
    return (
        <div>
            <h3>{topicid}</h3>
        </div>
    );
}